<template>
  <div class="modal-overlay" @click.self="close">
    <div class="modal-container">
      <div class="modal-header">
        <h3>{{ exam.paper_name }} - 添加考生</h3>
        <button class="close-btn" @click="close">
          <i class="fas fa-times"></i>
        </button>
      </div>

      <div class="modal-body">
        <div class="search-section">
          <div class="search-box">
            <i class="fas fa-search"></i>
            <input
                type="text"
                placeholder="搜索学生..."
                v-model="searchQuery"
                @input="handleSearch"
            >
          </div>
          <button class="btn btn-refresh" @click="refreshStudents">
            <i class="fas fa-sync-alt"></i> 刷新列表
          </button>
        </div>

        <div class="student-selection">
          <div class="selection-header">
            <div class="header-item">
              <input
                  type="checkbox"
                  id="select-all"
                  v-model="selectAll"
                  @change="toggleSelectAll"
              >
              <label for="select-all">全选</label>
            </div>
            <div class="header-item">学号</div>
            <div class="header-item">姓名</div>
            <div class="header-item">班级</div>
            <div class="header-item">上次成绩</div>
          </div>

          <div
              v-for="student in filteredStudents"
              :key="student.id"
              class="student-item"
              :class="{ 'selected': selectedStudents.includes(student.id) }"
          >
            <div class="item-cell">
              <input
                  type="checkbox"
                  :id="'student-' + student.id"
                  v-model="selectedStudents"
                  :value="student.id"
              >
            </div>
            <div class="item-cell">{{ student.id }}</div>
            <div class="item-cell">{{ student.name }}</div>
            <div class="item-cell">{{ student.class }}</div>
            <div class="item-cell">
              <span v-if="student.lastScore !== null" class="score-badge" :class="getScoreClass(student.lastScore)">
                {{ student.lastScore }}分
              </span>
              <span v-else class="score-badge no-score">无记录</span>
            </div>
          </div>

          <div v-if="loading" class="loading-state">
            <div class="spinner"></div>
            <p>加载中...</p>
          </div>

          <div v-if="!loading && filteredStudents.length === 0" class="empty-state">
            <i class="fas fa-user-graduate"></i>
            <p>没有找到匹配的学生</p>
          </div>
        </div>

        <div class="selection-summary">
          已选中 <span class="count">{{ selectedStudents.length }}</span> 名学生
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn btn-secondary" @click="close">
          <i class="fas fa-times"></i> 取消
        </button>
        <button
            class="btn btn-primary"
            @click="addStudents"
            :disabled="selectedStudents.length === 0 || isAdding"
        >
          <i class="fas fa-user-plus"></i>
          <span v-if="!isAdding">添加选中学生</span>
          <span v-else>添加中...</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'AddStudentsModal',
  props: {
    exam: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      searchQuery: '',
      selectedStudents: [],
      students: [],
      loading: false,
      isAdding: false,
      selectAll: false
    }
  },
  computed: {
    filteredStudents() {
      if (!this.searchQuery) return this.students;
      const query = this.searchQuery.toLowerCase();
      return this.students.filter(student =>
          student.name.toLowerCase().includes(query) ||
          student.id.toString().includes(query) ||
          student.class.toLowerCase().includes(query)
      );
    }
  },
  created() {
    this.fetchStudents();
  },
  methods: {
    async fetchStudents() {
      this.loading = true;
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 800));

        // 模拟数据
        this.students = [
          { id: 1001, name: '张三', class: '计算机1班', lastScore: 85 },
          { id: 1002, name: '李四', class: '计算机1班', lastScore: 72 },
          { id: 1003, name: '王五', class: '计算机2班', lastScore: 90 },
          { id: 1004, name: '赵六', class: '计算机2班', lastScore: null },
          { id: 1005, name: '钱七', class: '计算机3班', lastScore: 68 },
          { id: 1006, name: '孙八', class: '计算机3班', lastScore: 79 },
          { id: 1007, name: '周九', class: '计算机4班', lastScore: 92 },
          { id: 1008, name: '吴十', class: '计算机4班', lastScore: 81 }
        ];
      } catch (error) {
        console.error('获取学生列表失败:', error);
      } finally {
        this.loading = false;
      }
    },

    refreshStudents() {
      this.searchQuery = '';
      this.fetchStudents();
    },

    close() {
      this.$emit('close');
      this.searchQuery = '';
      this.selectedStudents = [];
      this.selectAll = false;
    },

    handleSearch() {
      this.selectAll = false;
    },

    toggleSelectAll() {
      if (this.selectAll) {
        this.selectedStudents = this.filteredStudents.map(student => student.id);
      } else {
        this.selectedStudents = [];
      }
    },

    getScoreClass(score) {
      if (score >= 90) return 'excellent';
      if (score >= 80) return 'good';
      if (score >= 60) return 'pass';
      return 'fail';
    },

    async addStudents() {
      this.isAdding = true;
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000));

        this.$emit('students-added', {
          examId: this.exam.paper_id,
          studentIds: this.selectedStudents
        });

        this.$notify({
          title: '添加成功',
          message: `已成功添加${this.selectedStudents.length}名学生到考试`,
          type: 'success'
        });

        this.close();
      } catch (error) {
        console.error('添加学生失败:', error);
        this.$notify({
          title: '添加失败',
          message: '添加学生时出现错误，请重试',
          type: 'error'
        });
      } finally {
        this.isAdding = false;
      }
    }
  },
  watch: {
    selectedStudents(newVal) {
      if (newVal.length === this.filteredStudents.length && this.filteredStudents.length > 0) {
        this.selectAll = true;
      } else {
        this.selectAll = false;
      }
    }
  }
}
</script>

<style lang="less" scoped>
@primary: #4361EE;
@primary-light: #A5B4FC;
@primary-lighter: #E0E7FF;
@secondary: #3A0CA3;
@success: #10B981;
@warning: #F59E0B;
@danger: #EF4444;
@gray-50: #F9FAFB;  // 添加这一行
@gray-100: #F3F4F6;
@gray-200: #E5E7EB;
@gray-300: #D1D5DB;
@gray-400: #9CA3AF;
@gray-500: #6B7280;
@gray-600: #4B5563;
@gray-700: #374151;
@gray-800: #1F2937;
@gray-900: #111827;

@shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
@shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);
@shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1);
@radius-sm: 0.375rem;
@radius-md: 0.5rem;
@radius-lg: 0.75rem;
@transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease-out;
}

.modal-container {
  background-color: white;
  border-radius: @radius-md;
  width: 90%;
  max-width: 900px;
  max-height: 85vh;
  display: flex;
  flex-direction: column;
  box-shadow: @shadow-lg;
  animation: slideUp 0.3s ease-out;
}

.modal-header {
  padding: 1.5rem;
  border-bottom: 1px solid @gray-200;
  display: flex;
  align-items: center;
  justify-content: space-between;

  h3 {
    margin: 0;
    font-size: 1.25rem;
    color: @gray-800;
    font-weight: 600;
  }

  .close-btn {
    background: none;
    border: none;
    font-size: 1.25rem;
    color: @gray-500;
    cursor: pointer;
    padding: 0.5rem;
    transition: @transition;
    border-radius: 50%;
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      background-color: @gray-100;
      color: @gray-700;
    }
  }
}

.modal-body {
  padding: 1.5rem;
  overflow-y: auto;
  flex: 1;
}

.search-section {
  display: flex;
  align-items: center;
  gap: 1rem;
  margin-bottom: 1.5rem;

  .search-box {
    flex: 1;
    position: relative;
    max-width: 400px;

    i {
      position: absolute;
      left: 1rem;
      top: 50%;
      transform: translateY(-50%);
      color: @gray-400;
      transition: @transition;
    }

    input {
      width: 100%;
      padding: 0.75rem 1rem 0.75rem 2.5rem;
      border: 1px solid @gray-300;
      border-radius: @radius-md;
      font-size: 0.9375rem;
      transition: @transition;
      background-color: white;

      &:focus {
        outline: none;
        border-color: @primary;
        box-shadow: 0 0 0 3px rgba(@primary, 0.1);

        + i {
          color: @primary;
        }
      }

      &::placeholder {
        color: @gray-400;
      }
    }
  }

  .btn-refresh {
    background-color: @gray-100;
    color: @gray-700;
    border: none;
    padding: 0.75rem 1rem;
    border-radius: @radius-md;
    font-size: 0.875rem;
    font-weight: 500;
    cursor: pointer;
    transition: @transition;
    display: flex;
    align-items: center;
    gap: 0.5rem;

    &:hover {
      background-color: @gray-200;
    }

    i {
      font-size: 0.875rem;
    }
  }
}

.student-selection {
  border: 1px solid @gray-200;
  border-radius: @radius-md;
  overflow: hidden;
  margin-bottom: 1.5rem;

  .selection-header {
    display: grid;
    grid-template-columns: 100px 100px 1fr 1fr 120px;
    background: @gray-100;
    font-weight: 600;
    color: @gray-700;
    font-size: 0.875rem;

    .header-item {
      padding: 0.75rem 1rem;
      border-right: 1px solid @gray-200;
      display: flex;
      align-items: center;
      gap: 0.5rem;

      &:last-child {
        border-right: none;
      }

      input[type="checkbox"] {
        width: 16px;
        height: 16px;
        accent-color: @primary;
        cursor: pointer;
      }

      label {
        cursor: pointer;
      }
    }
  }

  .student-item {
    display: grid;
    grid-template-columns: 100px 100px 1fr 1fr 120px;
    align-items: center;
    padding: 0.75rem 1rem;
    border-bottom: 1px solid @gray-200;
    font-size: 0.875rem;
    transition: @transition;

    &:hover {
      background-color: @gray-50;
    }

    &.selected {
      background-color: fade(@primary-lighter, 30%);
    }

    &:last-child {
      border-bottom: none;
    }

    .item-cell {
      padding: 0 0.5rem;

      input[type="checkbox"] {
        width: 16px;
        height: 16px;
        accent-color: @primary;
        cursor: pointer;
      }

      .score-badge {
        display: inline-block;
        padding: 0.25rem 0.5rem;
        border-radius: 1rem;
        font-size: 0.75rem;
        font-weight: 500;

        &.excellent {
          background: rgba(@success, 0.1);
          color: @success;
        }

        &.good {
          background: rgba(@primary, 0.1);
          color: @primary;
        }

        &.pass {
          background: rgba(@warning, 0.1);
          color: @warning;
        }

        &.fail {
          background: rgba(@danger, 0.1);
          color: @danger;
        }

        &.no-score {
          background: @gray-100;
          color: @gray-500;
        }
      }
    }
  }
}

.loading-state {
  padding: 2rem;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1rem;

  .spinner {
    width: 40px;
    height: 40px;
    border: 4px solid rgba(@primary, 0.1);
    border-top-color: @primary;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  p {
    margin: 0;
    color: @gray-600;
  }
}

.empty-state {
  padding: 2rem;
  text-align: center;
  color: @gray-500;

  i {
    font-size: 2rem;
    margin-bottom: 1rem;
    color: @gray-300;
  }

  p {
    margin: 0;
  }
}

.selection-summary {
  text-align: right;
  font-size: 0.875rem;
  color: @gray-700;
  margin-bottom: 1.5rem;

  .count {
    font-weight: 600;
    color: @primary;
    font-size: 1.125rem;
  }
}

.modal-footer {
  padding: 1rem 1.5rem;
  border-top: 1px solid @gray-200;
  display: flex;
  justify-content: flex-end;
  gap: 0.75rem;

  .btn {
    padding: 0.625rem 1.25rem;
    border-radius: @radius-sm;
    font-size: 0.9375rem;
    font-weight: 500;
    cursor: pointer;
    transition: @transition;
    border: none;
    display: flex;
    align-items: center;
    gap: 0.5rem;

    &.btn-primary {
      background-color: @primary;
      color: white;

      &:hover {
        background-color: darken(@primary, 5%);
      }

      &:disabled {
        background-color: @gray-300;
        color: @gray-600;
        cursor: not-allowed;
      }
    }

    &.btn-secondary {
      background-color: @gray-100;
      color: @gray-700;

      &:hover {
        background-color: @gray-200;
      }
    }
  }
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from { transform: translateY(20px); opacity: 0; }
  to { transform: translateY(0); opacity: 1; }
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .modal-container {
    width: 95%;
  }

  .search-section {
    flex-direction: column;
    align-items: stretch;

    .search-box {
      max-width: none;
    }
  }

  .student-selection {
    .selection-header, .student-item {
      grid-template-columns: 80px 80px 1fr;

      .header-item:nth-child(4),
      .item-cell:nth-child(4),
      .header-item:nth-child(5),
      .item-cell:nth-child(5) {
        display: none;
      }
    }
  }
}

@media (max-width: 480px) {
  .modal-header {
    padding: 1rem;

    h3 {
      font-size: 1.125rem;
    }
  }

  .modal-body {
    padding: 1rem;
  }

  .student-selection {
    .selection-header, .student-item {
      grid-template-columns: 60px 1fr;

      .header-item:nth-child(3),
      .item-cell:nth-child(3) {
        display: none;
      }
    }
  }

  .modal-footer {
    flex-direction: column;

    .btn {
      width: 100%;
      justify-content: center;
    }
  }
}
</style>